package com.liqi.quartz.task;

import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.utils.DateUtils;
import com.liqi.deployment.domain.DvOperationUser;
import com.liqi.dev.domain.CfgBranch;
import com.liqi.device.domain.TWorkingCalendar;

import com.liqi.device.service.TWorkingCalendarService;
import com.liqi.items.domain.TCfgBranch;
import com.liqi.items.service.ITCfgBranchService;
import com.liqi.sms.domain.SysShortMessage;
import com.liqi.sms.service.ISysShortMessageService;
import com.liqi.system.service.device.IDvOperationUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.liqi.deployment.domain.DvDeployment;
import com.liqi.deployment.service.IDvDeploymentService;
import com.liqi.monitor.domain.DvDeploymentSystem;
import com.liqi.monitor.domain.DvFaultLog;
import com.liqi.monitor.service.IDvDeploymentSystemService;
import com.liqi.monitor.service.IDvFaultLogService;
import com.liqi.system.service.ISysConfigService;
import org.springframework.web.client.RestTemplate;

@Component("heartbeatTask")
public class HeartbeatTask {
    private static final Logger log = LoggerFactory.getLogger(HeartbeatTask.class);

    @Autowired
    private IDvDeploymentSystemService deploymentSystemService;

    @Autowired
    private IDvDeploymentService dvDeploymentService;

    @Autowired
    private IDvFaultLogService dvFaultLogService;
    
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private TWorkingCalendarService calendarInfoService;
    @Autowired
    private ISysShortMessageService shortMessageService;
    @Autowired
    private IDvOperationUserService dvOperationUserService;
    @Autowired
    private ITCfgBranchService branchService;

    private DvDeploymentSystem dvEquipmentStatusLog = null;

    private String configKey = "heartbeat";//配置名称
    public void heartbeat()
    {
        System.out.println("心跳任务触发!!!!!");
        DvDeployment dvDeployment = null ;
        List<DvDeploymentSystem> list = deploymentSystemService.selectDvEquipmentSystemListForTask(dvEquipmentStatusLog);
        for (DvDeploymentSystem dvEquipmentStatusLog : list) {

            Date updateTime = dvEquipmentStatusLog.getUpdateTime();
            DvFaultLog log1 = new DvFaultLog();
            log1.setDeviceId(dvEquipmentStatusLog.getDeviceId());
            DvFaultLog dvFaultLog = dvFaultLogService.selectDvFaultLogByDeviceId(log1);
            String deviceId = dvEquipmentStatusLog.getDeviceId();
            //根据自编设备号 查询设备投放管理
            dvDeployment = dvDeploymentService.selectDvDeploymentByDeviceId(deviceId);
            Date openTime = dvDeployment.getOpenTime();
            Date closeTime = dvDeployment.getCloseTime();
            Integer service24 = dvDeployment.getService24();

            log.info("openTime="+openTime,"closeTime="+closeTime,"service24="+service24);


            //设备状态日志对象的更新时间不为空
            if (updateTime != null) {
                Calendar beforeTime = Calendar.getInstance();
                String configValue = sysConfigService.selectConfigByKey(configKey);//获取配置的心跳时间
                int amount = Integer.parseInt(configValue);
                beforeTime.add(Calendar.MINUTE,-amount);// 5分钟之前的时间
                Date beforeDate = beforeTime.getTime();
                boolean before = updateTime.before(beforeDate);
                //如果更新时间早于当前时间的5分钟之前
                if (before) {
                     //根据
                    if (dvDeployment != null) {
                        // 设备状态，0是正常，1是离线，2是当天异常
                        String deviceStatus = dvDeployment.getDeviceStatus();
                        if (deviceStatus!=null && !deviceStatus.equals("3")) {
                            dvDeployment.setDeviceStatus("2");
                            log.info("openTime=",(openTime),"closeTime="+closeTime,"service24="+service24,dvDeployment,dvFaultLog);

                            dvDeploymentService.updateDvDeployment(dvDeployment);
                        }                        
                        if (dvFaultLog != null) {
                            dvDeployment.setDeviceStatus("3");
                            judgeSendMessage(openTime,closeTime,service24,dvDeployment,dvFaultLog);

                            dvDeploymentService.updateDvDeployment(dvDeployment);
						}
                    }
                }
                //如果更新时间仅仅只有当前时间的5分钟之内，即不早于5分钟前
                else {
                    if (dvDeployment != null) {
                        String deviceStatus = dvDeployment.getDeviceStatus();
                        // 设备状态，0是正常，1是离线，2是当天异常
                        if (deviceStatus!=null && !deviceStatus.equals("3")) {
                            dvDeployment.setDeviceStatus("1");
                            dvDeploymentService.updateDvDeployment(dvDeployment);
                        }
                        if (dvFaultLog != null) {
                            dvDeployment.setDeviceStatus("3");
                            judgeSendMessage(openTime,closeTime,service24,dvDeployment,dvFaultLog);

                            dvDeploymentService.updateDvDeployment(dvDeployment);
						}
                    }
                }
            }
            //设备状态日志对象的更新时间为空
            else {
                if (dvDeployment != null) {
                    // 设备状态，0是正常，1是离线，2是当天异常
                    String deviceStatus = dvDeployment.getDeviceStatus();
                    if (deviceStatus!=null && !deviceStatus.equals("3")) {
                        dvDeployment.setDeviceStatus("2");
                        judgeSendMessage(openTime,closeTime,service24,dvDeployment,dvFaultLog);
                        dvDeploymentService.updateDvDeployment(dvDeployment);
                    }
                    if (dvFaultLog != null) {
                        dvDeployment.setDeviceStatus("3");
                        judgeSendMessage(openTime,closeTime,service24,dvDeployment,dvFaultLog);
                        dvDeploymentService.updateDvDeployment(dvDeployment);
					}
                }
            }
//              if (dvDeployDeviceManager!=null){
//                  insertOrUpdateByDvHeartBeat(dvDeployDeviceManager);
//              }
        }
    }
    public void sendMessage(DvDeployment dvDeployment,DvFaultLog dvFaultLog) {
        if(dvFaultLog==null){
            log.info("无异常日志");
            return;
        }
        DvOperationUser dvOperationUser = dvOperationUserService.selectDvOperationUserByOperationUserName(dvDeployment.getOperationUserName(), dvDeployment.getOperationUserCode());
        if(dvOperationUser==null){
            log.info("运维人员信息有误");
            return;
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String,Object> map = new HashMap<>();
        map.put("operationUserName", dvDeployment.getOperationUserName());
        map.put("nowTime",df.format(new Date()));
        map.put("deploymentName", dvDeployment.getDeploymentName());
        map.put("deviceId", dvDeployment.getDeviceId());
        map.put("deploymentAddress", dvDeployment.getAncestorsName()+ dvDeployment.getDeploymentAddress());
        if("2".equals(dvDeployment.getDeviceStatus())){
            map.put("errorMessage", "设备离线");
        }
        if("3".equals(dvDeployment.getDeviceStatus())){
            map.put("errorMessage", dvFaultLog.getErrorMessage());
        }
        if("5".equals(dvDeployment.getDeviceStatus())){
            map.put("errorMessage", "设备关机");
        }
        map.put("reportType","心跳上报");


        // 新建短信实体，并插入到短信实体数据库
        SysShortMessage sysShortMessage = new SysShortMessage();
        sysShortMessage.setCreateTime(DateUtils.getNowDate());
        sysShortMessage.setPhoneNumbers(dvOperationUser.getPhoneNumber());
        sysShortMessage.setSendFlag("0");

        String result = JSONUtils.toJSONString(map);
        sysShortMessage.setTemplateParam(result);
        sysShortMessage.setCreateBy("心跳上报");
        sysShortMessage.setCreateTime(new java.sql.Date(new java.util.Date().getTime()));
        log.info("插入短信成功");
        shortMessageService.insertSysShortMessage(sysShortMessage);
    }


    public void judgeSendMessage(Date openTime, Date closeTime ,Integer service24,DvDeployment dvDeployment,DvFaultLog dvFaultLog)
    {
        //true是工作日
        Boolean holidayInfo = isHolidayInfo(LocalDate.now());

        if(service24==1){
                sendMessage(dvDeployment,dvFaultLog);
        }
      else  if(holidayInfo){

            SimpleDateFormat df = new SimpleDateFormat("HH:mm"); // 设置日期格式
            Date now = null;


            try {
                now = df.parse(df.format(new Date()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        log.info("now+"+now, "openTime+"+openTime, "closeTime+"+closeTime);
            boolean flag = belongCalendar(now, openTime, closeTime);
            if (flag) {
                sendMessage(dvDeployment,dvFaultLog);
            }
        }



    }
    public Boolean isHolidayInfo(LocalDate localDate) {
        log.info("queryAlmanacs_param={}", localDate);
        try {
            TWorkingCalendar tWorkingCalendar = calendarInfoService.getOne(Wrappers.lambdaQuery(TWorkingCalendar.class).eq(TWorkingCalendar::getCalendarDate, localDate));
            if (tWorkingCalendar == null) {
                List<TWorkingCalendar> resrltCalendarInfos = new ArrayList<>();
                List<Integer> list = Arrays.asList(2, 5, 8, 11);
                list.forEach(o -> {
                    resrltCalendarInfos.addAll(calendarInfoService.resolveCalendarInfo(String.valueOf(localDate.getYear()), String.valueOf(o)));
                });

                for (TWorkingCalendar resrltCalendarInfo : resrltCalendarInfos) {
                    if (localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).equals(resrltCalendarInfo.getCalendarDate())) {
                        tWorkingCalendar = resrltCalendarInfo;
                    }
                }
            }
            if (tWorkingCalendar.getCalendarType() == null) {
                return "六".equals(tWorkingCalendar.getCnDay()) || "日".equals(tWorkingCalendar.getCnDay()) ? Boolean.TRUE : Boolean.FALSE;
            } else {
                return 1 == tWorkingCalendar.getCalendarType() ? Boolean.FALSE : Boolean.TRUE;
            }

        } catch (Exception e) {
            log.error("isHoliday_error!", e);
            if (DayOfWeek.SATURDAY.equals(localDate.getDayOfWeek()) || DayOfWeek.SUNDAY.equals(localDate.getDayOfWeek())) {
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        }

    }

    /**
     * 判断时间是否在时间段内
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        log.info("now+"+nowTime, "openTime+"+beginTime, "closeTime+"+endTime);
            if (nowTime.getTime() == beginTime.getTime() || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }



}
